# 机箱snmp操作类
from public._snmp import snmpget, snmpset,ping
from re import sub
from public.logger import getLogger
from src.cycle_calc import cycle_calc

from config.config import master_ip

class SNMP_proto():
    # 类初始化函数
    def __init__(self, data_list, index_dict, host_dict, name_dict):
        self.data_list = data_list
        self.index_dict = index_dict
        self.host_dict = host_dict
        self.name_dict = name_dict
        self.logger={}
        for data in set(self.name_dict.values()):
            # print(self.name_dict.values())
            self.logger[data] = getLogger(data)
        self.logger['WR']=getLogger('WR')

    # 机箱初始化函数

    def init_snmp(self):

        delay = {}
        width = {}
        enable = {}
        sync_status = {}
        time_sys = {}
        time_run = {}
        temperature = {}
        rtt = {}
        heartbeat_enable = {}
        portlinkstatus={}
        interlock_enbale={}
        print("Node 开始初始化，请稍候")
        for pvname,host in self.host_dict.items():
            if self.name_dict[pvname] == "Node":
                if ping(host):
                    file_path = "./WR-IMP-MIB-node.txt"
                    return_data = snmpget(OIDname="impCtrlHeartbeatEna",file_path= file_path, host=host)
                    if not "Error" in return_data:
                        try:
                            Enable_data = return_data.split("\n")[0]
                            msg = Enable_data.split("INTEGER:")
                            msg = sub("[^\d]", "", msg[1])
                            heartbeat_enable[pvname] = int(msg)
                        except:
                            heartbeat_enable[pvname] = -1
                            self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                    else:
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                    
                    return_data = snmpget(OIDname="impCtrlInterlockEna",file_path= file_path, host=host)
                    if not "Error" in return_data:
                        try:
                            Enable_data = return_data.split("\n")[0]
                            msg = Enable_data.split("INTEGER:")
                            msg = sub("[^\d]", "", msg[1])
                            interlock_enbale[pvname] = int(msg)
                        except:
                            interlock_enbale[pvname] = -1
                            self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                    else:
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))

                    return_data = snmpget(OIDname="impCtrlMENA",file_path= file_path, host=host)
                    if not "Error" in return_data:
                        try:
                            Enable_data = return_data.split("\n")[0]
                            msg = Enable_data.split("INTEGER:")
                            msg = sub("[^\d]", "", msg[1])
                            enable[pvname] = int(msg)
                        except:
                            enable[pvname] = -1
                            self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                    else:
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))

                    return_data = snmpget(OIDname="impWavePatternWidth.0", file_path=file_path,host=host)
                    if not "Error" in return_data:
                        try:
                            msg = return_data.split("Gauge32:")
                            msg = sub("[^\d]", "", msg[1])
                            width[pvname] = float(msg) / 250
                        except:
                            width[pvname] = -1
                            self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                    else:
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))

                    return_data = snmpget(OIDname="impWavePatternDelay.0", file_path=file_path,host=host)
                    if not "Error" in return_data:
                        try:
                            msg = return_data.split("Gauge32:")
                            msg = sub("[^\d]", "", msg[1])
                            delay[pvname] = float(msg) / 250
                        except:
                            delay[pvname] = -1
                            self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                    else:
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                    file_path = "./WR-WRPC-MIB.txt"
                    # 读取同步状态
                    return_data = snmpget(OIDname="wrpcPtpServoStateN.0", file_path=file_path, host=host)
                    if not "Error" in return_data:
                        try:
                            # print(return_data)
                            msg = return_data.split("INTEGER:")[-1].strip()
                            if "(" in msg and ")" in msg:
                                status_value = int(msg[msg.index("(") + 1: msg.index(")")]) 
                            else:
                                status_value = 6  
                            # print(msg)
                            if status_value < 0 or status_value >5 :
                                status_value = 6
                            sync_status[pvname] = status_value
                        except:
                            
                            # self.logger['WR'].debug("Host:{} sync status parse Wrong !!!".format(host))
                            sync_status[pvname] = 6
                    else:
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                    # 读取系统时间
                    return_data = snmpget(OIDname="wrpcTimeTAIString.0", file_path=file_path, host=host)
                    if not "Error" in return_data:
                        try:
                            time_sys[pvname] = return_data.split("STRING:")[-1].strip()
                        except:
                            # self.logger['WR'].debug("Host:{} system time parse Wrong !!!".format(host))
                            time_sys[pvname] = "Error"
                    else:
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                    # 读取系统运行时间
                    return_data = snmpget(OIDname="wrpcTimeSystemUptime.0", file_path=file_path, host=host)
                    if not "Error" in return_data:
                        try:
                            time_run[pvname] = return_data.split("Timeticks:")[-1].strip()
                        except:
                            # self.logger['WR'].debug("Host:{} system uptime parse Wrong !!!".format(host))
                            time_run[pvname] = "Error"
                    else:
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                    # 读取温度
                    return_data = snmpget(OIDname="wrpcTemperatureValue.1", file_path=file_path, host=host)
                    if not "Error" in return_data:
                        try:
                            temperature[pvname] = float(return_data.split("STRING:")[-1].strip())
                        except:
                            # self.logger['WR'].debug("Host:{} temperature parse Wrong !!!".format(host))
                            temperature[pvname] = -1
                    else:
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                    # 读取往返延迟 (RTT)
                    return_data = snmpget(OIDname="wrpcPtpRTT.0", file_path=file_path, host=host)
                    if not "Error" in return_data:
                        try:
                            rtt[pvname] = int(return_data.split("Counter64:")[-1].strip())
                        except:
                            # self.logger['WR'].debug("Host:{} RTT parse Wrong !!!".format(host))
                            rtt[pvname] = -1
                    else:
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                    # 读取连接状态
                    return_data = snmpget(OIDname="wrpcPortLinkStatus", file_path=file_path, host=host)
                    if not "Error" in return_data:
                        try:
                            msg = return_data.split("INTEGER:")[-1].strip()
                            # print("linkstatus",msg)
                            if "(" in msg and ")" in msg:
                                linkstatus = int(msg[msg.index("(") + 1: msg.index(")")]) 
                                # print(linkstatus)
                            else:
                                linkstatus = 0  
                            portlinkstatus[pvname] = linkstatus
                        except:
                            # self.logger['WR'].debug("Host:{} portlinkstatus parse Wrong !!!".format(host))
                            portlinkstatus[pvname] = 0
                    else:
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
                else:
                    self.logger['WR'].debug("Host:{} init Wrong !!!".format(host))
        print("Node 初始化完成")
        print("multi 机箱开始初始化，请稍候")
        for data in self.data_list:
            # 读取 Enable 数据
            if ping(data["host"]):
                file_path = "./WR-IMP-MIB-multi.txt"
                return_data = snmpget(OIDname="impCtrlMENA",file_path= file_path, host=data["host"])
                if not "Error" in return_data:
                # print(return_data)
                # self.logger[data["name"]].debug(return_data)
                    try:
                        Enable_list = return_data.split("\n")[0:10]
                        for key, value in data["data"].items():
                            msg = Enable_list[value].split("INTEGER:")
                            msg = sub("[^\d]", "", msg[1])
                            enable[key] = int(msg)
                    except Exception as e:
                        for key, value in data["data"].items():
                            enable[key] = -1
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))
                else:
                    self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))

                return_data = snmpget(OIDname="impCtrlInterlockEna",file_path= file_path, host=data["host"])
                if not "Error" in return_data:
                # print(return_data)
                # self.logger[data["name"]].debug(return_data)
                    try:
                        Enable_list = return_data.split("\n")[0:10]
                        for key, value in data["data"].items():
                            msg = Enable_list[value].split("INTEGER:")
                            msg = sub("[^\d]", "", msg[1])
                            interlock_enbale[key] = int(msg)
                    except Exception as e:
                        for key, value in data["data"].items():
                            interlock_enbale[key] = -1
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))
                else:
                    self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))

                # 读取 Delay 和 Width 数据
                return_data = snmpget(
                    OIDname="impWavePatternTable1", file_path= file_path,host=data["host"])
                if not "Error" in return_data:
                    try:
                        Delay_list = return_data.split("\n")[0:10]
                        Width_list = return_data.split("\n")[10:20]
                        for key, value in data["data"].items():
                            msg = Delay_list[value].split("Gauge32:")
                            msg = sub("[^\d]", "", msg[1])
                            delay[key] = float(msg) / 250

                            msg = Width_list[value].split("Gauge32:")
                            msg = sub("[^\d]", "", msg[1])
                            width[key] = float(msg) / 250
                    except:
                        for key, value in data["data"].items():
                            delay[key] = -1
                            width[key] = -1
                        self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))
                        continue
                else:
                    self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))

                file_path = "./WR-WRPC-MIB.txt"
                host = data["host"]
                # 读取同步状态
                return_data = snmpget(OIDname="wrpcPtpServoStateN.0", file_path=file_path, host=host)
                if not "Error" in return_data:
                    try:
                        # print(return_data)
                        msg = return_data.split("INTEGER:")[-1].strip()
                        if "(" in msg and ")" in msg:
                            status_value = int(msg[msg.index("(") + 1: msg.index(")")]) 
                        else:
                            status_value = 6  
                        # print(msg)
                        if status_value < 0 or status_value >5 :
                            status_value = 6
                    except:
                        
                        # self.logger['WR'].debug("Host:{} sync status parse Wrong !!!".format(host))
                        sync_status[pvname] = 6
                    finally:
                        for pvname in data["data"].keys():
                            sync_status[pvname] = status_value
                else:
                    self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))
                # 读取系统时间
                return_data = snmpget(OIDname="wrpcTimeTAIString.0", file_path=file_path, host=host)
                if not "Error" in return_data:
                    try:
                        time_sys_data = return_data.split("STRING:")[-1].strip()
                    except:
                        # self.logger['WR'].debug("Host:{} system time parse Wrong !!!".format(host))
                        time_sys_data = "Error"
                    finally:
                        for pvname in data["data"].keys():
                            time_sys[pvname] = time_sys_data
                else:
                    self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))
                # 读取系统运行时间
                return_data = snmpget(OIDname="wrpcTimeSystemUptime.0", file_path=file_path, host=host)
                if not "Error" in return_data:
                    try:
                        time_run_data = return_data.split("Timeticks:")[-1].strip()
                    except:
                        # self.logger['WR'].debug("Host:{} system uptime parse Wrong !!!".format(host))
                        time_run_data = "Error"
                    finally:
                        for pvname in data["data"].keys():
                            time_run[pvname] = time_run_data
                else:
                    self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))
                # 读取温度
                return_data = snmpget(OIDname="wrpcTemperatureValue.1", file_path=file_path, host=host)
                if not "Error" in return_data:
                    try:
                        temperature_data = float(return_data.split("STRING:")[-1].strip())
                    except:
                        # self.logger['WR'].debug("Host:{} temperature parse Wrong !!!".format(host))
                        temperature_data = -1
                    finally:
                        for pvname in data["data"].keys():
                            temperature[pvname] = temperature_data
                else:
                    self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))
                # 读取往返延迟 (RTT)
                return_data = snmpget(OIDname="wrpcPtpRTT.0", file_path=file_path, host=host)
                if not "Error" in return_data:
                    try:
                        rtt_data = int(return_data.split("Counter64:")[-1].strip())
                    except:
                        # self.logger['WR'].debug("Host:{} RTT parse Wrong !!!".format(host))
                        rtt_data = -1
                    finally:
                        for pvname in data["data"].keys():
                            rtt[pvname] = rtt_data
                else:
                    self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))
                # 读取连接状态
                return_data = snmpget(OIDname="wrpcPortLinkStatus", file_path=file_path, host=host)
                if not "Error" in return_data:
                    try:
                        msg = return_data.split("INTEGER:")[-1].strip()
                        # print("linkstatus",msg)
                        if "(" in msg and ")" in msg:
                            linkstatus = int(msg[msg.index("(") + 1: msg.index(")")]) 
                            # print(linkstatus)
                        else:
                            linkstatus = 0  
                    except:
                        # self.logger['WR'].debug("Host:{} portlinkstatus parse Wrong !!!".format(host))
                        linkstatus = 0
                    finally:
                        for pvname in data["data"].keys():
                            portlinkstatus[pvname] = linkstatus
                else:
                    self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))
            else:
                self.logger['WR'].debug("Host:{} init Wrong !!!".format(data["host"]))
        print("multi 机箱初始化完成")

        # 返回读取的数据
        return {
            "delay": delay,
            "width": width,
            "enable": enable,
            "sync_status": sync_status,
            "time_sys": time_sys,
            "time_run": time_run,
            "temperature": temperature,
            "rtt": rtt,
            "portlinkstatus":portlinkstatus,
            "heartbeat_enable":heartbeat_enable,
            "interlock_enable":interlock_enbale
        }

    # status_monitor
    def status_monitor(self):
        sync_status = {}
        time_sys = {}
        time_run = {}
        temperature = {}
        rtt = {}
        portlinkstatus={}
        for pvname, host in self.host_dict.items():
            file_path = "./WR-WRPC-MIB.txt"
            if self.name_dict[pvname] == "Node":
                # 读取同步状态
                return_data = snmpget(OIDname="wrpcPtpServoStateN.0", file_path=file_path, host=host)
                if not "Error" in return_data:
                    try:
                        # print(return_data)
                        msg = return_data.split("INTEGER:")[-1].strip()
                        if "(" in msg and ")" in msg:
                            status_value = int(msg[msg.index("(") + 1: msg.index(")")]) 
                        else:
                            status_value = 6  
                        # print(msg)
                        if status_value < 0 or status_value >5 :
                            status_value = 6
                        sync_status[pvname] = status_value
                    except:
                        self.logger['WR'].debug("Host:{} sync status parse Wrong !!!".format(host))
                        sync_status[pvname] = 6
                        continue

                # 读取系统时间
                return_data = snmpget(OIDname="wrpcTimeTAIString.0", file_path=file_path, host=host)
                if not "Error" in return_data:
                    try:
                        time_sys[pvname] = return_data.split("STRING:")[-1].strip()
                    except:
                        self.logger['WR'].debug("Host:{} system time parse Wrong !!!".format(host))
                        time_sys[pvname]='error'
                        continue
                # 读取系统运行时间
                return_data = snmpget(OIDname="wrpcTimeSystemUptime.0", file_path=file_path, host=host)
                if not "Error" in return_data:
                    try:
                        time_run[pvname] = return_data.split("Timeticks:")[-1].strip()
                    except:
                        self.logger['WR'].debug("Host:{} system uptime parse Wrong !!!".format(host))
                        time_run[pvname]='error'
                        continue

                # 读取温度 读取数据有问题，再检查
                return_data = snmpget(OIDname="wrpcTemperatureValue.1", file_path=file_path, host=host)
                if not "Error" in return_data:
                    try:
                        temperature[pvname] = float(return_data.split("STRING:")[-1].strip())
                    except:
                        self.logger['WR'].debug("Host:{} temperature parse Wrong !!!".format(host))
                        temperature[pvname]=-1
                        continue
                
                # 读取往返延迟 (RTT)
                return_data = snmpget(OIDname="wrpcPtpRTT.0", file_path=file_path, host=host)
                if not "Error" in return_data:
                    try:
                        rtt[pvname] = int(return_data.split("Counter64:")[-1].strip())
                    except:
                        self.logger['WR'].debug("Host:{} RTT parse Wrong !!!".format(host))
                        rtt[pvname]=-1
                        continue
                # 读取连接状态
                return_data = snmpget(OIDname="wrpcPortLinkStatus", file_path=file_path, host=host)
                if not "Error" in return_data:
                    try:
                        msg = return_data.split("INTEGER:")[-1].strip()
                        # print("linkstatus",msg)
                        if "(" in msg and ")" in msg:
                            linkstatus = int(msg[msg.index("(") + 1: msg.index(")")]) 
                            # print(linkstatus)
                        else:
                            linkstatus = 0  
                        portlinkstatus[pvname] = linkstatus
                    except:
                        self.logger['WR'].debug("Host:{} portlinkstatus parse Wrong !!!".format(host))
                        portlinkstatus[pvname] = 0
                        continue
        for data in self.data_list:
            host = data["host"]
            file_path = "./WR-WRPC-MIB.txt"
            # 读取同步状态
            return_data = snmpget(OIDname="wrpcPtpServoStateN.0", file_path=file_path, host=host)
            if not "Error" in return_data:
                try:
                    # print(return_data)
                    msg = return_data.split("INTEGER:")[-1].strip()
                    if "(" in msg and ")" in msg:
                        status_value = int(msg[msg.index("(") + 1: msg.index(")")]) 
                    else:
                        status_value = 6  
                    # print(msg)
                    if status_value < 0 or status_value >5 :
                        status_value = 6
                    for pvname in data["data"].keys():
                        sync_status[pvname] = status_value
                except:
                    self.logger['WR'].debug("Host:{} sync status parse Wrong !!!".format(host))
                    for pvname in data["data"].keys():
                        sync_status[pvname] = 6
                    continue

            # 读取系统时间
            return_data = snmpget(OIDname="wrpcTimeTAIString.0", file_path=file_path, host=host)
            if not "Error" in return_data:
                try:
                    for pvname in data["data"].keys():
                        time_sys[pvname] = return_data.split("STRING:")[-1].strip()
                except:
                    self.logger['WR'].debug("Host:{} system time parse Wrong !!!".format(host))
                    for pvname in data["data"].keys():
                        time_sys[pvname]='error'
                    continue
            # 读取系统运行时间
            return_data = snmpget(OIDname="wrpcTimeSystemUptime.0", file_path=file_path, host=host)
            if not "Error" in return_data:
                try:
                    for pvname in data["data"].keys():
                        time_run[pvname] = return_data.split("Timeticks:")[-1].strip()
                except:
                    self.logger['WR'].debug("Host:{} system uptime parse Wrong !!!".format(host))
                    for pvname in data["data"].keys():
                        time_run[pvname]='error'
                    continue
            # 读取温度 程序读取有问题，后续再检查
            """return_data = snmpget(OIDname="wrpcTemperatureValue.1", file_path=file_path, host=host)
            if not "Error" in return_data:
                try:
                    for pvname in data["data"].keys():
                        temperature[pvname] = float(return_data.split("STRING:")[-1].strip())
                except:
                    self.logger['WR'].debug("Host:{} temperature parse Wrong !!!".format(host))
                    for pvname in data["data"].keys():
                        temperature[pvname]=-1
                    continue"""
            
            # 读取往返延迟 (RTT)
            return_data = snmpget(OIDname="wrpcPtpRTT.0", file_path=file_path, host=host)
            if not "Error" in return_data:
                try:
                    for pvname in data["data"].keys():
                        rtt[pvname] = int(return_data.split("Counter64:")[-1].strip())
                except:
                    self.logger['WR'].debug("Host:{} RTT parse Wrong !!!".format(host))
                    for pvname in data["data"].keys():
                        rtt[pvname]=-1
                    continue
            # 读取连接状态
            return_data = snmpget(OIDname="wrpcPortLinkStatus", file_path=file_path, host=host)
            if not "Error" in return_data:
                try:
                    msg = return_data.split("INTEGER:")[-1].strip()
                    # print("linkstatus",msg)
                    if "(" in msg and ")" in msg:
                        linkstatus = int(msg[msg.index("(") + 1: msg.index(")")]) 
                        # print(linkstatus)
                    else:
                        linkstatus = 0
                    for pvname in data["data"].keys():
                        portlinkstatus[pvname] = linkstatus
                except:
                    self.logger['WR'].debug("Host:{} portlinkstatus parse Wrong !!!".format(host))
                    for pvname in data["data"].keys():
                        portlinkstatus[pvname] = 0
                    continue
        # 返回读取的数据
        return {
            "sync_status": sync_status,
            "time_sys": time_sys,
            "time_run": time_run,
            "temperature": temperature,
            "rtt": rtt,
            "portlinkstatus":portlinkstatus
        }
    # 保存机箱参数
    def save(self,host,pvname):
        
        if self.name_dict[pvname] == "Node":
            file_path = "./WR-IMP-MIB-node.txt"
        elif self.host_dict[pvname] == master_ip:
            file_path = "./WR-IMP-MIB-mas.txt"
        else:
            file_path = "./WR-IMP-MIB-multi.txt"
        return_data = snmpset(host=host,file_path=file_path,
                                OIDname="impCtrlApply.0", mask="INTEGER:", set_type="i", set_value=3)
        print(f"host:{host},pvname:{pvname},return data:{return_data}")
        # for data in self.data_list:
        #     return_data = snmpset(host=data["host"],
        #                           OIDname="impCtrlApply.0", mask="INTEGER:", set_type="i", set_value=3)
        #     print("impCtrlApply.0: ", return_data)
            # self.loggeimpWavePatternTable1r[data["name"]].info("impCtrlApply.0: ", return_data)
    # 机箱触发模式读取函数
    def Trigger_Status(self,pvname):
        triggerstatus={}
        if self.name_dict[pvname] == "Node":
            file_path = "./WR-IMP-MIB-node.txt"
        else:
            file_path = "./WR-IMP-MIB-multi.txt"
        return_data = snmpget(OIDname="impCtrlTrigger",file_path= file_path, host=self.host_dict[pvname])
        msg = return_data
        # print("触发snmp",return_data)
        if not "Error" in return_data:
            try:
                Enable_data = return_data.split("\n")[0]
                msg = Enable_data.split("Gauge32:")
                msg = sub("[^\d]", "", msg[1])
                    # print(msg)
            except:
                self.logger['WR'].debug("Host:{} init Wrong !!!".format(self.host_dict[pvname]))
                msg = "Host:{} init Wrong !!!".format(self.host_dict[pvname])
        return msg
    
    # 机箱参数下发函数

    def SNMP_opr(self, pvname, FREQ, Width_us, Delay_us, Enable):
        if ping(self.host_dict[pvname]):
            self.logger[self.name_dict[pvname]].info("FREQ:{} Hz\tEnable:{}\tWidth:{} us\tDelay:{} us".format(
                FREQ, Enable, Width_us, Delay_us))

            _100ms_num, _4ns_num = cycle_calc(FREQ, Width_us, Delay_us)
            # self.logger[self.name_dict[pvname]].info("100ms:{}\t\t4ns:{}".format(
            #         _100ms_num, _4ns_num))
            self.logger[self.name_dict[pvname]].info("100ms:{}\t\t4ns:{}".format(
                    _100ms_num, _4ns_num))
            
            enable=self.enable(pvname=pvname, value=Enable)
            self.PatternMC(pvname=pvname)
            width=self.width(pvname=pvname, Width_us=Width_us)
            delay=self.delay(pvname=pvname, Delay_us=Delay_us)
            self.idle_100ms(pvname=pvname, _100ms_num=_100ms_num)
            self.idle_4ns(pvname=pvname, _4ns_num=_4ns_num)
            self.PatternSet(pvname=pvname)
            return enable,width,delay
        else:
            return -1,-1,-1
        
    def get_interlock(self,host,device):
        try:
            if device == "Node":
                file_path = "./WR-IMP-MIB-node.txt"
                OIDname="impLocalInterlock.0"
                if ping(host):
                    return_data = snmpget(host=host,file_path=file_path,
                                        OIDname=OIDname)
                    if not "Error" in return_data:
                        msg = return_data.split("Gauge32:")
                        msg = sub("[^\d]", "", msg[1])
                        interlock = int(msg)
                        # self.logger[self.name_dict[pvname]].debug(
                        #     "impCtrlApply.0 ", return_data)
                        return interlock
                else:
                    return -1
        except:
            return -1
        
        if device == "Master":
            file_path = "./WR-IMP-MIB-mas.txt"
            OIDname="impInterlock7100.0"
            if ping(host):
                return_data = snmpget(host=host,file_path=file_path,
                                    OIDname=OIDname)
                
                if not "Error" in return_data:
                    msg = return_data.split("Gauge32:")
                    
                    msg = sub("[^\d]", "", msg[1])
                    
                    interlock = int(msg)
                    # self.logger[self.name_dict[pvname]].debug(
                    #     "impCtrlApply.0 ", return_data)
                    return interlock
            else:
                print("master 网络不通")
                return -1
        
    # 使能修改函数
    def get_UTC(self,host):
        try:
            
            file_path = "./WR-WRPC-MIB.txt"
            OIDname="wrpcTimeTAIString.0"
            if ping(host):
                return_data = snmpget(host=host,file_path=file_path,
                                    OIDname=OIDname)
                # print(return_data)
                if not "Error" in return_data:
                    msg = return_data.split("STRING:")
                    # self.logger[self.name_dict[pvname]].debug(
                    #     "impCtrlApply.0 ", return_data)
                    return msg[1]
            else:
                return -1
        except:
            return -1
    # 使能修改函数

    def heartbeat_enable(self, pvname, value):
        if self.name_dict[pvname] == "Node":
            file_path = "./WR-IMP-MIB-node.txt"
        else:
            file_path = "./WR-IMP-MIB-multi.txt"
        if ping(self.host_dict[pvname]):
            return_data = snmpset(host=self.host_dict[pvname],file_path=file_path,
                                OIDname="impCtrlHeartbeatEna", mask="INTEGER:", set_type="i", set_value=value)
            return_data = snmpget(host=self.host_dict[pvname],file_path=file_path,
                                OIDname="impCtrlHeartbeatEna")
            if not "Error" in return_data:
                msg = return_data.split("INTEGER:")
                msg = sub("[^\d]", "", msg[1])
                value = int(msg)
                self.logger[self.name_dict[pvname]].debug(
                    "impCtrlHeartbeatEna: ", value)
                
                # print("impCtrlMC{}Ena: ".format(self.index_dict[pvname]), return_data)
                return_data = snmpset(OIDname="impCtrlApply.0", file_path=file_path,host=self.host_dict[pvname],
                                    mask="INTEGER:", set_type="i", set_value=11)
                self.logger[self.name_dict[pvname]].debug(
                    "impCtrlApply.0 ", return_data)
                # self.logger[self.name_dict[pvname]].debug(
                #     "impCtrlApply.0 ", return_data)
                return value
        return -1
        # print("impCtrlApply.0 ", return_data)
    def reset(self):
        file_path = "./WR-IMP-MIB-mas.txt"
        if ping(master_ip):
            return_data = snmpset(file_path=file_path,host=master_ip,OIDname="impCtrlApply.0",set_type="i",set_value=31,mask="INTEGER:")
    # 使能修改函数
    def waitover(self):
        file_path = "./WR-IMP-MIB-mas.txt"
        if ping(master_ip):
            return_data = snmpget(file_path=file_path,host=master_ip,OIDname="impOvertime")
            if not "Error" in return_data:
                msg = return_data.split("Gauge32:")
                msg = sub("[^\d]", "", msg[1])
                enable = int(not int(msg))
                return enable
            else:
                return -1
        else:
            return -1
    def enable(self, pvname, value):
        if self.name_dict[pvname] == "Node":
            file_path = "./WR-IMP-MIB-node.txt"
        else:
            file_path = "./WR-IMP-MIB-multi.txt"
        if ping(self.host_dict[pvname]):
            return_data = snmpset(host=self.host_dict[pvname],file_path=file_path,
                                OIDname="impCtrlMC{}Ena".format(self.index_dict[pvname]), mask="INTEGER:", set_type="i", set_value=value)
            return_data = snmpget(host=self.host_dict[pvname],file_path=file_path,
                                OIDname="impCtrlMC{}Ena".format(self.index_dict[pvname]))
            if not "Error" in return_data:
                msg = return_data.split("INTEGER:")
                msg = sub("[^\d]", "", msg[1])
                enable = int(msg)
                self.logger[self.name_dict[pvname]].debug(
                    "impCtrlMC{}Ena: ".format(self.index_dict[pvname]), enable)
                
                # print("impCtrlMC{}Ena: ".format(self.index_dict[pvname]), return_data)
                return_data = snmpset(OIDname="impCtrlApply.0", file_path=file_path,host=self.host_dict[pvname],
                                    mask="INTEGER:", set_type="i", set_value=11)
                # self.logger[self.name_dict[pvname]].debug(
                #     "impCtrlApply.0 ", return_data)
                return enable
        else:
            return -1
        # print("impCtrlApply.0 ", return_data)
    # 脉宽修改函数

    def PatternMC(self, pvname):
        if self.name_dict[pvname] == "Node":
            file_path = "./WR-IMP-MIB-node.txt"
        else:
            file_path = "./WR-IMP-MIB-multi.txt"
        return_data = snmpset(host=self.host_dict[pvname],file_path=file_path,
                              OIDname="impWavePatternMC.0", mask="INTEGER:", set_type="i", set_value=self.index_dict[pvname])
        return_data = snmpset(host=self.host_dict[pvname],file_path=file_path,
                              OIDname="WavePatternIndexMC0", mask="INTEGER:", set_type="i", set_value=self.index_dict[pvname])
        # self.logger[self.name_dict[pvname]].debug(
        #     "impWavePatternMC: ", return_data)
        # print("impWavePatternMC: ", return_data)

    def PatternSet(self, pvname):
        if self.name_dict[pvname] == "Node":
            file_path = "./WR-IMP-MIB-node.txt"
        else:
            file_path = "./WR-IMP-MIB-multi.txt"
        return_data = snmpset(OIDname="impWavePatternSet.0",file_path=file_path, host=self.host_dict[pvname],
                              mask="INTEGER:", set_type="i", set_value=1)
        # self.logger[self.name_dict[pvname]].debug(
        #     "impWavePatternSet.0 ", return_data)
        # print("impWavePatternSet.0 ", return_data)

    def width(self, pvname, Width_us):
        if self.name_dict[pvname] == "Node":
            file_path = "./WR-IMP-MIB-node.txt"
        else:
            file_path = "./WR-IMP-MIB-multi.txt"
        if ping(self.host_dict[pvname]):
            return_data = snmpset(OIDname="impWavePatternWidth.0", file_path=file_path,host=self.host_dict[pvname],
                                mask="Gauge32:", set_type="u", set_value=int(Width_us*250))
            return_data = snmpget(OIDname="impWavePatternWidth.0", file_path=file_path,host=self.host_dict[pvname])
            if not "Error" in return_data:
                msg = return_data.split("Gauge32:")
                msg = sub("[^\d]", "", msg[1])
                width = float(msg) / 250
                self.logger[self.name_dict[pvname]].debug(
                    "Width us:", width)
                return width
        else:
            return -1

    # 延时修改函数
    def delay(self, pvname, Delay_us):
        if self.name_dict[pvname] == "Node":
            file_path = "./WR-IMP-MIB-node.txt"
        else:
            file_path = "./WR-IMP-MIB-multi.txt"
        if ping(self.host_dict[pvname]):
            return_data = snmpset(OIDname="impWavePatternDelay.0", file_path=file_path,host=self.host_dict[pvname],
                                mask="Gauge32:", set_type="u", set_value=int(Delay_us*250))
            return_data = snmpget(OIDname="impWavePatternDelay.0", file_path=file_path,host=self.host_dict[pvname])
            if not "Error" in return_data:
                msg = return_data.split("Gauge32:")
                msg = sub("[^\d]", "", msg[1])
                delay= float(msg) / 250
                self.logger[self.name_dict[pvname]].debug(
                    "Delay us:", delay)
                return delay
        else:
            return -1

    # 4ns idle延时修改函数
    def idle_4ns(self, pvname, _4ns_num):
        if self.name_dict[pvname] == "Node":
            file_path = "./WR-IMP-MIB-node.txt"
        else:
            file_path = "./WR-IMP-MIB-multi.txt"
        return_data = snmpset(OIDname="impWavePatternIdle4ns.0", file_path=file_path,host=self.host_dict[pvname],
                              mask="Gauge32:", set_type="u", set_value=int(_4ns_num))
        # self.logger[self.name_dict[pvname]].debug("4nm:", return_data)
    # 100ms idle延时修改函数

    def idle_100ms(self, pvname, _100ms_num):
        if self.name_dict[pvname] == "Node":
            file_path = "./WR-IMP-MIB-node.txt"
        else:
            file_path = "./WR-IMP-MIB-multi.txt"
        return_data = snmpset(OIDname="impWavePatternIdle100ms.0", file_path=file_path,host=self.host_dict[pvname],
                              mask="Gauge32:", set_type="u", set_value=int(_100ms_num))
        # self.logger[self.name_dict[pvname]].debug(
        #     "100ms:", return_data)
